/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BARelatedMaterialsListViewController.m
//  redia-bapps-ios
//
//  Created by Mads Darø Kristensen on 10/9/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BARelatedMaterialsListViewController.h"
#import "BASearchResultCell.h"
#import "BAUtils.h"
#import "BASearchResultsTableViewController.h"
#import "BACollection.h"
#import "BARecord.h"
#import "BAFlyoutMenuViewController.h"
#import "MWFSlideNavigationViewController.h"

@interface BARelatedMaterialsListViewController ()

@property (strong, nonatomic) BASearchResultsTableViewController *tableViewController;
@property (strong, nonatomic) BASearchResult *lastSearchResult;
@property (assign, nonatomic) NSInteger offset;
@property (assign, nonatomic) BOOL isFetchingMoreResults;

@end

@implementation BARelatedMaterialsListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
    RD_SET_EDGES_FOR_EXTENDED_LAYOUT_IOS7
    BA_FLYOUT_MENU_ADD_BUTTON(BASpecialNavigationBarConfigurationDefault);
    
    BA_LABEL_SET_FONT_LIGHT(self.headerLabel);
    self.headerLabel.text = self.headerText ? self.headerText : @"";
    
    self.tableViewController = [[BASearchResultsTableViewController alloc] init];
    self.tableViewController.dataSource = self;
    [self addChildViewController:self.tableViewController];
    [self.contentView addSubview:self.tableViewController.view];
    self.tableViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[table]-0-|"
                                                                            options:0
                                                                            metrics:0
                                                                              views:@{@"table": self.tableViewController.view}]];
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[table]-0-|"
                                                                            options:0
                                                                            metrics:0
                                                                              views:@{@"table": self.tableViewController.view}]];

    if (self.headerText) {
        self.headerLabel.text = self.headerText;
    }
    
    if (self.relatedMaterialsData) {
        if (self.relatedMaterialsData.searchResult) {
            [self.tableViewController appendSearchResult:self.relatedMaterialsData.searchResult];
        }
        else if (self.relatedMaterialsData.records) {
            [self.tableViewController appendRecords:self.relatedMaterialsData.records];
        }
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self enableUserInteraction];
}

- (void)setRelatedMaterialsData:(BARelatedMaterialsData *)relatedMaterialsData
{
    _relatedMaterialsData = relatedMaterialsData;
    _offset = 0;
    self.lastSearchResult = relatedMaterialsData.searchResult;
    if ([self isViewLoaded]) {
        [self.tableViewController appendSearchResult:relatedMaterialsData.searchResult];
    }
}

- (void)setHeaderText:(NSString *)headerText
{
    _headerText = headerText;
    if ([self isViewLoaded]) {
        self.headerLabel.text = headerText;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)loadDataFromIdentifiers:(NSArray *)faustIdentifiers
{
    [self view];
    self.tableViewController.view.hidden = YES;
    
    if ([faustIdentifiers count]>0){
        [self.loadingIndicator startAnimating];

        [BARPCManager searchAsyncFromView:self
                                    query:@""
                                   filter:@{@"identifier":faustIdentifiers}
                                    count:20
                                   offset:0
                              resultBlock:^(BASearchResult *result) {
                                  [self.loadingIndicator stopAnimating];
                                  self.tableViewController.view.hidden=NO;
                                  
                                  BARelatedMaterialsData* materialsData = [BARelatedMaterialsData new];
                                  materialsData.relationType = BA_RELATED_MATERIAL_TYPE_NEWS_AND_ARRANGEMENTS_MATERIALS;
                                  materialsData.searchResult = result;
                                  materialsData.faustIdentifiers = faustIdentifiers;
                                  
                                  [self setRelatedMaterialsData:materialsData];
                              }
                               errorBlock:^(int errorCode, NSString *errorMessage) {
                                   [self.loadingIndicator stopAnimating];
                               }];
        
    }
}

#pragma mark - BASearchResultsTableViewControllerDataSource

- (BOOL)hasMoreResults
{
    return (self.lastSearchResult != nil && self.lastSearchResult.more);
}

- (void)loadMoreResults
{
    // Quit if we are already trying to fetch more results.
    if (self.isFetchingMoreResults) {
        return;
    }
    
    switch (self.relatedMaterialsData.relationType) {
        case BA_RELATED_MATERIAL_TYPE_MORE_BY_AUTHOR:
        {
            self.offset += 20;
            self.isFetchingMoreResults = YES;
            [BARPCManager getMoreByCreatorFromView:self
                                        identifier:self.relatedMaterialsData.identifier
                                            offset:self.offset
                                             count:20
                                           filters:nil
                                            facets:nil
                                       resultBlock:^(BASearchResult *result) {
                                           self.lastSearchResult = result;
                                           if (result != nil && result.count > 0) {
                                               [self.tableViewController appendSearchResult:result];
                                           }
                                           else {
                                               self.offset -= 20;
                                           }
                                           self.isFetchingMoreResults = NO;
                                       }
                                        errorBlock:^(int errorCode, NSString *errorMessage) {
                                            DLog(@"Error fetching more results. Error code=%d, message\"%@\"", errorCode, errorMessage);
                                            self.isFetchingMoreResults = NO;
                                        }];
        }
            break;
            
        case BA_RELATED_MATERIAL_TYPE_MORE_IN_SERIES:
        {
            self.offset += 20;
            self.isFetchingMoreResults = YES;
            [BARPCManager getMoreInSameSeriesAsyncFromView:self
                                        identifier:self.relatedMaterialsData.identifier
                                            offset:self.offset
                                             count:20
                                           filters:nil
                                            facets:nil
                                       resultBlock:^(BASearchResult *result) {
                                           self.lastSearchResult = result;
                                           if (result != nil && result.count > 0) {
                                               [self.tableViewController appendSearchResult:result];
                                           }
                                           else {
                                               self.offset -= 20;
                                           }
                                           self.isFetchingMoreResults = NO;
                                       }
                                        errorBlock:^(int errorCode, NSString *errorMessage) {
                                            DLog(@"Error fetching more results. Error code=%d, message\"%@\"", errorCode, errorMessage);
                                            self.isFetchingMoreResults = NO;
                                        }];
        }
            break;
            
        case BA_RELATED_MATERIAL_TYPE_NEWS_AND_ARRANGEMENTS_MATERIALS:
        {
            self.offset += 20;
            self.isFetchingMoreResults = YES;
            [BARPCManager searchAsyncFromView:self
                                        query:@""
                                       filter:@{@"identifier":self.relatedMaterialsData.faustIdentifiers}
                                        count:20
                                       offset:self.offset
                                  resultBlock:^(BASearchResult *result) {
                                      self.lastSearchResult = result;
                                      if (result != nil && result.count > 0) {
                                          [self.tableViewController appendSearchResult:result];
                                      }
                                      else {
                                          self.offset -= 20;
                                      }
                                      self.isFetchingMoreResults = NO;
                                    }
                                   errorBlock:^(int errorCode, NSString *errorMessage) {
                                       DLog(@"Error fetching more results. Error code=%d, message\"%@\"", errorCode, errorMessage);
                                       self.isFetchingMoreResults = NO;
                                   }];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - Fetch data autonomously

-(void)loadDataFromRecord:(BARecord*)record withRelationType:(NSInteger)relationType
{
    [self view];
    [self.loadingIndicator startAnimating];
    self.contentView.hidden=YES;
    
    switch (relationType) {
        case BA_RELATED_MATERIAL_TYPE_MORE_BY_AUTHOR:
        {
            self.isFetchingMoreResults = YES;
            [BARPCManager getMoreByCreatorFromView:self
                                        identifier:record.identifier
                                            offset:0
                                             count:20
                                           filters:nil
                                            facets:nil
                                       resultBlock:^(BASearchResult *result) {
                                           if ([result count]>0) {
                                               BARelatedMaterialsData *data = [BARelatedMaterialsData new];
                                               data.searchResult = result;
                                               data.relationType = BA_RELATED_MATERIAL_TYPE_MORE_BY_AUTHOR;
                                               data.identifier = record.identifier;
                                               [self setRelatedMaterialsData:data];
                                               self.contentView.hidden=NO;
                                           } else {
                                               // Should not happen, fail silently
                                           }
                                           [self.loadingIndicator stopAnimating];

                                       }
                                        errorBlock:^(int errorCode, NSString *errorMessage) {
                                            DLog(@"Error fetching more results. Error code=%d, message\"%@\"", errorCode, errorMessage);
                                            [[[UIAlertView alloc] initWithTitle:@"Kunne ikke indlæse relaterede materialer" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil] show];
                                            [self.loadingIndicator stopAnimating];
                                        }];
        }
            break;
        case BA_RELATED_MATERIAL_TYPE_MORE_IN_SERIES:
        {
            self.isFetchingMoreResults = YES;
            [BARPCManager getMoreInSameSeriesAsyncFromView:self
                                                identifier:record.identifier
                                                    offset:0
                                                     count:20
                                                   filters:nil
                                                    facets:nil
                                               resultBlock:^(BASearchResult *result) {
                                                   if ([result count]>0) {
                                                       BARelatedMaterialsData *data = [BARelatedMaterialsData new];
                                                       data.searchResult = result;
                                                       data.relationType = BA_RELATED_MATERIAL_TYPE_MORE_IN_SERIES;
                                                       data.identifier = record.identifier;
                                                       [self setRelatedMaterialsData:data];
                                                       self.contentView.hidden=NO;
                                                   } else {
                                                       // Should not happen, fail silently
                                                   }
                                                   [self.loadingIndicator stopAnimating];
                                               }
                                                errorBlock:^(int errorCode, NSString *errorMessage) {
                                                    DLog(@"Error fetching more results. Error code=%d, message\"%@\"", errorCode, errorMessage);
                                                    [[[UIAlertView alloc] initWithTitle:@"Kunne ikke indlæse relaterede materialer" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil] show];
                                                    [self.loadingIndicator stopAnimating];
                                                }];
        }
            break;
        default:
            break;
    }
}

#pragma mark - Flyout menu

BA_FLYOUT_MENU_ADD_CALLBACK

- (void)enableUserInteraction
{
    self.view.userInteractionEnabled = YES;
    self.tabBarController.tabBar.userInteractionEnabled = YES;
}

- (void)disableUserInteraction
{
    self.view.userInteractionEnabled = NO;
    self.tabBarController.tabBar.userInteractionEnabled = NO;
}

@end
